<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <el-form-item label="发货单号">
        <el-input v-model="queryParams.shipmentCode" placeholder="请输入发货单号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="createDate" type="daterange" range-separator="—" start-placeholder="开始时间"
          end-placeholder="结束时间" format="yyyy-MM-dd" value-format="yyyy-MM-dd" clearable />
      </el-form-item>
      <el-form-item label="平台单号">
        <el-input v-model="queryParams.platformOrderCode" placeholder="请输入平台单号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="会员名称">
        <el-input v-model="queryParams.clientName" placeholder="请输入会员名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="收货人">
        <el-input v-model="queryParams.consignee" placeholder="请输入收货人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="仓库名称">
        <el-select v-model="queryParams.warehouseName" placeholder="请选择仓库" filterable>
          <el-option v-for="item in warehouseList" :key="item.warehouseName" :label="item.warehouseName" :value="item.warehouseName" />
        </el-select>
      </el-form-item>
      <el-form-item label="店铺名称">
        <el-select v-model="queryParams.shopId" placeholder="请选择店铺" clearable>
          <el-option v-for="item in shopList" :key="item.id" :label="item.shopName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="物流单号">
        <el-input v-model="queryParams.expressCode" placeholder="请输入物流单号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="物流公司">
        <el-select v-model="queryParams.expressCompany" placeholder="请选择物流公司" clearable style="width: 100%">
          <el-option v-for="item in expressCompanyOptions" :key="item.id" :label="item.platformName" :value="item.platformName" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态">
        <el-select v-model="orderStatus" placeholder="请选择订单状态" clearable>
           <el-option
              v-for="dict in dict.type.order_progress"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
        </el-select>
      </el-form-item>
      <el-form-item label="打印状态">
        <el-select v-model="queryParams.printStatus" placeholder="请选择打印状态" clearable>
          <el-option v-for="item in dict.type.print_status" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <!-- 发货单标识 -->
      <el-form-item label="发货单标识">
        <el-select v-model="queryParams.deliveryFlag" placeholder="请选择发货单标识" clearable style="width: 100%">
          <el-option v-for="item in [{ value: '销售发货', label: '销售发货' }, { value: '售后发货', label: '售后发货' }]" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否拦截">
        <el-checkbox v-model="intercepted" />
      </el-form-item>
      <el-form-item label="是否作废">
        <el-checkbox v-model="isCancel" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格功能 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button plain size="mini" @click="handlePrintDelivery">打印发货单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain size="mini" @click="handlePrintLogistics">打印物流单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain size="mini" @click="handleUpdateLogisticsInfo">修改物流/发货信息</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-dropdown @command="handlePrintStatusCommand">
          <el-button plain size="mini">批量修改打印状态<i class="el-icon-arrow-down el-icon--right"></i></el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="deliveryUnprinted">发货单未打印</el-dropdown-item>
            <el-dropdown-item command="deliveryPrinted">发货单已打印</el-dropdown-item>
            <el-dropdown-item command="logisticsUnprinted">物流单未打印</el-dropdown-item>
            <el-dropdown-item command="logisticsPrinted">物流单已打印</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
      <el-col :span="1.5">
        <el-button plain size="mini" @click="handleBatchUpdateExpress">批量修改物流公司</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-dropdown @command="handleMultiPackageCommand">
          <el-button plain size="mini">获取多包裹<i class="el-icon-arrow-down el-icon--right"></i></el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="getMultiPackage">获取多包裹</el-dropdown-item>
            <el-dropdown-item command="updateMultiPackage">修改多包裹</el-dropdown-item>
            <el-dropdown-item command="cancelMultiPackage">取消多包裹</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
      <el-col :span="1.5">
        <el-button plain size="mini" @click="handleCancelDelivery">作废</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain size="mini" @click="handleFillLogisticsCode">填充物流单号</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-dropdown @command="handleExportCommand">
          <el-button plain size="mini">导出<i class="el-icon-arrow-down el-icon--right"></i></el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="exportDelivery">发货单数据</el-dropdown-item>
            <el-dropdown-item command="exportPackage">包裹数据</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
      <el-col :span="1.5">
        <el-button plain size="mini" @click="handleReprintLogistics">补打物流单</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格信息、分页 -->
    <div class="app-container-main">
      <vxe-table border stripe v-loading="loading" ref="tableRef" size="small" header-align="center"
        :row-config="rowConfig" :column-config="columnConfig" @checkbox-change="checkboxChangeEvent"
        @checkbox-all="checkboxAll" @cell-click="cellClickEvent" :data="tableData">
        <vxe-column type="checkbox" width="80" fixed="left" drag-sort />
        <vxe-column type="seq" title="序号" width="60" fixed="left" align="center" />
        <vxe-column field="shipmentCode" title="发货单号" width="150" fixed="left" align="center" show-overflow="title" />
        <vxe-column field="orderCode" title="订单编号" width="150" align="center" show-overflow="title" />
        <vxe-column field="platformOrderCode" title="平台单号" width="150" align="center" show-overflow="title" />
        <vxe-column field="printStatus" title="打印状态" width="100" align="center" show-overflow="title" />
        <vxe-column field="shipmentBillPrinter" title="发货单是否打印" width="130" align="center" show-overflow="title" >
          <template #default="{ row }">
            <span>{{ row.shipmentBillPrinter && row.shipmentBillPrinter !== null ? '是' : '否' }}</span>
          </template>
        </vxe-column>
        <vxe-column field="shipmentBillPrintSeq" title="送货单打印批次-流水号" width="180" align="center"
          show-overflow="title" />
        <vxe-column field="expressBillPrinter" title="物流单是否打印" width="130" align="center" show-overflow="title" >
          <template #default="{ row }">
            <span>{{ row.expressBillPrinter && row.expressBillPrinter !== null ? '是' : '否' }}</span>
          </template>
        </vxe-column>
        <vxe-column field="expressBillPrintSeq" title="物流单打印批次-流水号" width="180" align="center"
          show-overflow="title" />
        <vxe-column field="multiPackage" title="是否多包裹/字母件" width="150" align="center" show-overflow="title" >
          <template #default="{ row }">
            <span>{{ row.multiPackage && row.multiPackage !== null ? '是' : '否' }}</span>
          </template>
        </vxe-column>
        <vxe-column field="warehouseName" title="仓库" width="120" align="center" show-overflow="title" />
        <vxe-column field="expressCompany" title="物流公司" width="120" align="center" show-overflow="title" />
        <vxe-column field="platformName" title="平台类型" width="100" align="center" show-overflow="title" />
        <vxe-column field="shopName" title="店铺" width="120" align="center" show-overflow="title" />
        <vxe-column field="clientName" title="会员名称" width="120" align="center" show-overflow="title" />
        <vxe-column field="productName" title="商品信息" width="200" align="center" show-overflow="title" />
        <vxe-column field="orderCount" title="商品数量？" width="100" align="center" show-overflow="title" />
        <vxe-column field="payAmount" title="应收金额？" width="120" align="center" show-overflow="title" />
        <vxe-column field="buyerRemark" title="买家留言" width="150" align="center" show-overflow="title" />
        <vxe-column field="sellerRemark" title="卖家备注" width="150" align="center" show-overflow="title" />
        <vxe-column field="extInfo" title="附加信息" width="150" align="center" show-overflow="title" />
        <vxe-column field="address" title="收货信息？" width="200" align="center" show-overflow="title" />
        <vxe-column field="auditUser" title="审核人？" width="100" align="center" show-overflow="title" />
        <vxe-column field="auditTime" title="审核时间？" width="150" align="center" show-overflow="title" />
        <vxe-column field="isRefund" title="是否退款？" width="100" align="center" show-overflow="title" />
        <vxe-column field="createTime" title="创建时间" width="150" align="center" show-overflow="title" />
        <vxe-column field="intercepted" title="是否拦截" width="100" align="center" show-overflow="title" >
          <template #default="{ row }">
            <span>{{ row.intercepted && row.intercepted !== null ? '是' : '否' }}</span>
          </template>
        </vxe-column>
        <vxe-column field="cancelled" title="是否作废" width="100" align="center" show-overflow="title" >
          <template #default="{ row }">
            <span>{{ row.cancelled && row.cancelled !== null ? '是' : '否' }}</span>
          </template>
        </vxe-column>
        <vxe-column field="deliveryCancelStatus" title="发货单作废状态？" width="130" align="center" show-overflow="title" />
      </vxe-table>

      <pagination v-show="total >= 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>

    <!-- 底部tab -->
    <div class="app-container-footer">
      <el-tabs v-model="activeName" type="border-card" :lazy="true">
        <el-tab-pane label="销售订单明细" name="1">
          <Property :cellId="cellId" />
        </el-tab-pane>
        <el-tab-pane label="商品明细" name="2">
          <Goods :cellId="cellId" :readonly="true" />
        </el-tab-pane>
        <el-tab-pane label="收货信息" name="3">
          <Address :cellId="cellId" :readonly="true" />
        </el-tab-pane>
        <el-tab-pane label="包裹信息" name="4">
          <Package :cellId="cellId" :readonly="true" />
        </el-tab-pane>
        <el-tab-pane label="操作日志" name="5">
          <operation :cellId="cellId" />
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 批量操作弹窗 -->
    <el-dialog :visible.sync="batchDialog.visible" :title="batchDialog.type === 'warehouse'
        ? '批量修改仓库'
        : batchDialog.type === 'express'
          ? '批量修改物流公司'
          : batchDialog.type === 'stock'
            ? '批量转为现货订单'
            : batchDialog.type === 'bizUser'
              ? '批量修改业务员'
              : batchDialog.type === 'extraInfo'
                ? '批量修改附加信息'
                : batchDialog.type === 'expectDelivery'
                  ? '批量修改预计发货时间'
                  : ''
      " width="400px" @close="handleBatchCancel">
      <el-form v-if="batchDialog.type === 'warehouse'" label-width="100px">
        <el-form-item label="仓库名称">
          <!-- <el-input v-model="batchForm.warehouseName" placeholder="请输入新仓库名称" /> -->
        <el-select v-model="batchForm.warehouseName" placeholder="请选择仓库" filterable>
          <el-option v-for="item in warehouseList" :key="item.warehouseName" :label="item.warehouseName" :value="item.warehouseName" />
        </el-select>
        </el-form-item>
      </el-form>
      <el-form v-if="batchDialog.type === 'express'" label-width="100px">
        <el-form-item label="物流公司">
          <el-select v-model="batchForm.expressCompany" placeholder="请选择物流公司" clearable style="width: 100%">
            <el-option v-for="item in expressCompanyOptions" :key="item.id" :label="item.platformName" :value="item.platformName" />
          </el-select>
        </el-form-item>
      </el-form>
      <div v-if="batchDialog.type === 'stock'" style="padding: 20px 0; text-align: center">
        确定将选中订单转为现货订单？
      </div>
      <el-form v-if="batchDialog.type === 'bizUser'" label-width="100px">
        <el-form-item label="新业务员">
          <el-select v-model="batchForm.bizUserId" placeholder="请选择业务员" filterable>
            <el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-form v-if="batchDialog.type === 'extraInfo'" label-width="100px">
        <el-form-item label="附加信息">
          <el-input v-model="batchForm.extraInfo" type="textarea" placeholder="请输入附加信息" />
        </el-form-item>
      </el-form>
      <el-form v-if="batchDialog.type === 'expectDelivery'" label-width="120px">
        <el-form-item label="预计发货时间">
          <el-date-picker v-model="batchForm.expectDelivery" type="date" placeholder="请选择预计发货时间"
            value-format="yyyy-MM-dd" style="width: 100%" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleBatchSubmit">确 定</el-button>
        <el-button @click="handleBatchCancel">取 消</el-button>
      </div>
      <div class="upload-area" v-if="batchDialog.type === 'import'">
        <el-upload ref="upload" :limit="1" accept=".xlsx,.xls" :show-file-list="false"
          :http-request="handleImportUpload" drag>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <div class="el-upload__tip" slot="tip">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate">下载模板</el-link>
          </div>
        </el-upload>
      </div>
    </el-dialog>

    <!-- 打印发货单对话框 -->
    <el-dialog :visible.sync="printDeliveryDialog.visible" title="打印发货单" width="800px"
      @close="printDeliveryDialog.visible = false">
      <div class="delivery-print-container" v-loading="printDeliveryDialog.loading">
        <!-- 发货单内容 -->
        <div class="delivery-print-content" v-if="printDeliveryDialog.deliveryData">
          <!-- 头部标题和二维码 -->
          <div class="delivery-header">
            <div class="delivery-title">
              <h2 class="title-text">发货单</h2>
            </div>
            <div class="delivery-qrcode">
              <div class="qr-code">
                <canvas ref="qrCanvas" width="80" height="80"></canvas>
              </div>
              <div class="delivery-code">{{ printDeliveryDialog.deliveryData.shipmentCode }}</div>
              <div class="delivery-time">{{ printDeliveryDialog.deliveryData.shipmentTime }}</div>
            </div>
          </div>

          <!-- 基础信息 -->
          <div class="delivery-info">
            <div class="info-left">
              <div class="info-row">
                <span class="label">店铺名称：</span>
                <span class="value">{{ printDeliveryDialog.deliveryData.shopName }}</span>
              </div>
              <div class="info-row">
                <span class="label">会员名称：</span>
                <span class="value">{{ printDeliveryDialog.deliveryData.clientName }}</span>
              </div>
              <div class="info-row">
                <span class="label">收货地址：</span>
                <span class="value">{{ printDeliveryDialog.deliveryData.address }}</span>
              </div>
              <div class="info-row">
                <span class="label">买家留言：</span>
                <span class="value">{{ printDeliveryDialog.deliveryData.buyerRemark }}</span>
              </div>
              <div class="info-row">
                <span class="label">卖家备注：</span>
                <span class="value">{{ printDeliveryDialog.deliveryData.sellerRemark }}</span>
              </div>
            </div>
            <div class="info-right">
              <div class="info-row">
                <span class="label">手机号：</span>
                <span class="value">{{ printDeliveryDialog.deliveryData.phone }}</span>
              </div>
              <div class="info-row">
                <span class="label">订单编号？：</span>
                <span class="value">{{ printDeliveryDialog.deliveryData.orderCode }}</span>
              </div>
            </div>
          </div>

          <!-- 商品明细表格 -->
          <div class="delivery-table">
            <table class="goods-table">
              <thead>
                <tr>
                  <th>序号</th>
                  <th>商品名称</th>
                  <th>规格</th>
                  <th>数量</th>
                  <th>让利后金额</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in printDeliveryDialog.deliveryData.goodsList" :key="index">
                  <td>{{ index + 1 }}</td>
                  <td>{{ item.platformProductName }}</td>
                  <td>{{ item.platformProductSpecification }}</td>
                  <td>{{ item.quantity }}</td>
                  <td>{{ item.onSaleAmount }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        <div v-else class="no-preview">暂无预览，请稍候</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmPrintDelivery" :loading="printDeliveryDialog.printing">打印</el-button>
        <el-button @click="printDeliveryDialog.visible = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 打印物流单对话框 -->
    <el-dialog :visible.sync="printLogisticsDialog.visible" title="打印物流单" width="600px"
      @close="printLogisticsDialog.visible = false">
      <div class="print-preview" v-loading="printLogisticsDialog.loading">
        <img :src="printLogisticsDialog.previewUrl" v-if="printLogisticsDialog.previewUrl" class="print-preview-image"
          alt="物流单预览" />
        <div v-else class="no-preview">暂无预览，请稍候</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmPrintLogistics" :loading="printLogisticsDialog.printing">打印</el-button>
        <el-button @click="printLogisticsDialog.visible = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 修改物流/收货信息对话框 -->
    <el-dialog 
      :visible.sync="updateLogisticsDialog.visible" 
      title="修改物流/收货信息" 
      width="1200px"
      @close="updateLogisticsDialog.visible = false"
      :close-on-click-modal="false"
    >
      <!-- 物流信息标签页 -->
      <div class="logistics-table">
        <table class="el-table" style="width: 100%">
          <thead>
            <tr>
              <th>序号</th>
              <th>物流单号</th>
              <th>物流公司</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in updateLogisticsForm.logisticsItems" :key="item.id">
              <td>{{ index + 1 }}</td>
              <td>
                <el-input size="small" v-model="item.expressCode" placeholder="请输入物流单号" disabled/>
              </td>
              <td>
                <el-select size="small" v-model="item.expressCompany" placeholder="请选择物流公司" filterable style="width: 100%">
                  <el-option v-for="company in expressCompanyOptions" :key="company.id" :label="company.platformName" :value="company.platformName" />
                </el-select>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 收货信息标签页 -->
      <el-form :model="updateLogisticsForm.receivingInfo" label-width="80px">
        <!-- 收货人和电话 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="收货人" required>
              <el-input v-model="updateLogisticsForm.receivingInfo.consignee" placeholder="请输入收货人" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收货电话">
              <el-input v-model="updateLogisticsForm.receivingInfo.tel" placeholder="请输入收货电话" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收货手机" required>
              <el-input v-model="updateLogisticsForm.receivingInfo.phone" placeholder="请输入收货手机" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 真实姓名和身份证 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="真实姓名">
              <el-input v-model="updateLogisticsForm.receivingInfo.realName" placeholder="请输入真实姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="身份证">
              <el-input v-model="updateLogisticsForm.receivingInfo.idCard" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮编">
              <el-input v-model="updateLogisticsForm.receivingInfo.postcode" placeholder="请输入邮编" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 省市区 手动输入 -->
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="省市区" required>
              <el-input v-model="updateLogisticsForm.receivingInfo.addrBrief" placeholder="请输入省" />
            </el-form-item>
          </el-col>

          <!-- 详细地址 -->
          <el-col :span="16">
            <el-form-item label="收货地址" required>
              <el-input v-model="updateLogisticsForm.receivingInfo.address" type="textarea" placeholder="请输入详细地址" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 备注 -->
        <el-form-item label="备注">
          <el-input v-model="updateLogisticsForm.receivingInfo.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmUpdateLogistics"
          :loading="updateLogisticsDialog.loading">确定</el-button>
        <el-button @click="updateLogisticsDialog.visible = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 填充物流单号对话框 -->
    <el-dialog :visible.sync="fillLogisticsDialog.visible" title="填充物流单号" width="800px"
      @close="fillLogisticsDialog.visible = false">
      <div v-loading="fillLogisticsDialog.loading" class="fill-logistics-table">
        <!-- 物流单号列表表格 -->
        <el-table :data="fillLogisticsForm.packageList" border size="small" style="width: 100%">
          <el-table-column prop="index" label="序号" width="80" align="center">
            <template slot-scope="{ $index }">
              {{ $index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="shipmentCode" label="送货单号" width="150" align="center" />
          <el-table-column prop="packageCode" label="包裹号" width="150" align="center" />
          <el-table-column prop="expressNo" label="物流单号" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.expressNo" placeholder="请输入" size="small" />
            </template>
          </el-table-column>
        </el-table>
        
        <el-alert 
          title="填充说明" 
          type="info" 
          description="请为每个包裹填写对应的物流单号，物流单号不能为空。" 
          show-icon 
          :closable="false"
          style="margin-top: 15px" 
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmFillLogistics" :loading="fillLogisticsDialog.loading">确定</el-button>
        <el-button @click="fillLogisticsDialog.visible = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 多包裹操作弹窗 -->
    <el-dialog :visible.sync="multiPackageDialog.visible" :title="getMultiPackageDialogTitle()" width="400px"
      @close="multiPackageDialog.visible = false" class="multi-package-dialog">
      <div v-loading="multiPackageDialog.loading">
        <!-- 获取多包裹 和 修改多包裹 显示包裹数量输入框 -->
        <div v-if="multiPackageDialog.type === 'get' || multiPackageDialog.type === 'update'">
          <el-form label-width="100px">
            <el-form-item label="包裹数量" required>
              <el-input-number v-model="multiPackageDialog.packageCount" :min="2" :max="99" size="small" style="width: 100%" />
            </el-form-item>
          </el-form>
          <el-alert 
            :title="multiPackageDialog.type === 'get' ? '获取多包裹说明' : '修改多包裹说明'" 
            type="info" 
            :description="multiPackageDialog.type === 'get' ? '设置包裹数量后将为该订单生成多个包裹' : '修改当前订单的包裹数量'"
            show-icon 
            :closable="false"
          />
        </div>
        
        <!-- 取消多包裹 显示确认提示 -->
        <div v-else-if="multiPackageDialog.type === 'cancel'" class="multi-package-confirm">
          确定要取消该订单的多包裹设置吗？取消后将合并为单个包裹。
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmMultiPackageOperation" :loading="multiPackageDialog.loading">
          {{ multiPackageDialog.type === 'cancel' ? '确认取消' : '确定' }}
        </el-button>
        <el-button @click="multiPackageDialog.visible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPrintManagement,
  printDelivery,
  printLogistics,
  updateLogisticsInfo,
  confirmLogisticsPrinted,
  getMultiPackage,
  cancelMultiPackage,
  updateMultiPackage,
  cancelDelivery,
  fillLogisticsCode,

  getOrderItems,
  getProductItems,
  getConsigneeInfo,
  getPackageLogisticsInfo,
  // exportDeliveryData,
  // exportPackageData,
} from "@/api/mes/sales/print";
import { listWarehouse } from "@/api/mes/wm/warehouse";
import { listShopBasic } from "@/api/mes/sales/shopBasic";
import { listPlatforms } from "@/api/mes/sales/platform";
import { checkboxMethods } from "./methods";
import { listUser } from "@/api/system/user";
import Property from "./components/property.vue";
import Address from "./components/address.vue";
import Goods from "./components/goods.vue";
import Operation from "./components/operation.vue";
import Package from "./components/package.vue";

export default {
  name: "PrintManagement",
  dicts: ["currency_type", 'platform_type', 'order_progress', 'print_status'],
  mixins: [checkboxMethods],
  components: {
    Property,
    Address,
    Goods,
    Operation,
    Package,
  },
  data() {
    return {
      showSearch: true,
      addTabActive: "goods",
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      isCancel: false,
      intercepted: false,
      createDate: this.getDefaultDateRange(),
      expressCompanyOptions: [],
      printStatusOptions: [
        { label: "未打印", value: "0" },
        { label: "已打印", value: "1" },
      ],
      warehouseList: [],
      shopList: [],
      tableData: [],
      total: 0,
      columnConfig: {
        drag: true,
        resizable: true,
        storage: true,
        sortConfig: {
          trigger: "cell",
          remote: true,
        },
        align: "center",
        headerAlign: "center",
      },
      rowConfig: {
        drag: true,
        keyField: "id",
        isHover: true,
        isCurrent: true,
      },
      activeName: "1",
      activeIndex: 1,
      loading: false,
      cellId: "",
      title: "",
      open: false,
      form: {},
      rules: {
        // shopType:[{ required: true, message: '请输入店铺类型', trigger: 'blur' }],
        // shopCode:[{ required: true, message: '请输入店铺编码', trigger: 'blur' }],
        // shopName:[{ required: true, message: '请选择店铺名称', trigger: 'blur' }],
      },
      userList: [],
      ids: [],
      batchDialog: {
        visible: false,
        type: "", // warehouse, express, stock
      },
      batchForm: {
        warehouseName: "",
        expressCompany: "",
      },
      // 打印发货单对话框
      printDeliveryDialog: {
        visible: false,
        loading: false,
        printing: false,
        previewUrl: "",
        deliveryIds: [],
        deliveryData: null,
      },
      // 打印物流单对话框
      printLogisticsDialog: {
        visible: false,
        loading: false,
        printing: false,
        previewUrl: "",
        deliveryIds: [],
      },
      // 修改物流/发货信息对话框
      updateLogisticsDialog: {
        visible: false,
        loading: false,
        activeTab: "logistics", // 默认显示物流信息标签页
      },
      updateLogisticsForm: {
        // 物流信息（每个发货单各自的物流信息）
        logisticsItems: [],
        // 收货信息（共享的收货信息）
        receivingInfo: {
          consignee: "",       // 收货人
          tel: "",           // 收货电话
          phone: "",          // 收货手机
          addrBrief: "",        // 省市区
          address: "",         // 详细地址
          postcode: ""          // 邮编
        },
        deliveryIds: [],
      },
      // 填充物流单号对话框
      fillLogisticsDialog: {
        visible: false,
        loading: false,
      },
      fillLogisticsForm: {
        packageList: [], // 包裹列表数据
        deliveryIds: [],
      },
      // 多包裹操作弹窗
      multiPackageDialog: {
        visible: false,
        loading: false,
        type: '', // 操作类型：get, update, cancel
        packageCount: 2, // 包裹数量
      },
      isUploading: false,
    };
  },
  created() {
    this.getList();
    listUser({ pageNum: 1, pageSize: 9999, orderStatus: "audit" }).then(
      (response) => {
        this.userList = response.rows;
      }
    );
    this.getShopList();
    this.getWarehouseList();
    setTimeout(() => {
      this.getLogisticsCompanyList()
    }, 100);
  },
  methods: {
    // 获取物流公司
    getLogisticsCompanyList(){
      listPlatforms({
        platformType: this.dict.type.platform_type.filter(item => item.label === '物流平台')[0].value,
        enabled: 1,
        pageNum: 1,
        pageSize: 9999,
      }).then(response => {
        this.expressCompanyOptions = response.rows;
      })
    },
    // 仓库下拉数据
    getWarehouseList(){
      listWarehouse({
        pageNum: 1,
        pageSize: 9999,
      }).then(response => {
        this.warehouseList = response.rows;
      })
    },
    // 店铺下拉数据
    getShopList(){
      listShopBasic({
        enabled: 1,
        pageNum: 1,
        pageSize: 9999
      }).then(response => {
        this.shopList = response.rows;
      })
    },

    // 打印发货单
    handlePrintDelivery() {
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择要打印的发货单");
        return;
      }
      
      // 获取选中的发货单数据
      const selectedRow = this.tableData.find(item => this.ids.includes(item.id));
      if (!selectedRow) {
        this.$modal.msgError("未找到发货单数据");
        return;
      }

      this.printDeliveryDialog.loading = true;
      this.printDeliveryDialog.deliveryIds = this.ids;

      printDelivery(this.ids)
      .then((res) => {
        if(res.data.length === 0) {
          this.$modal.msgError("未找到发货单数据");
          return;
        }else{
          const data = res.data[0]; // 假设只打印第一个发货单
          this.printDeliveryDialog.deliveryData = {
            shipmentCode: data.shipmentCode,
            shopName: data.shopName ,
            phone: data.phone , 
            clientName: data.clientName ,
            orderCode: data.orderCode,
            address: data.address ,
            buyerRemark: data.buyerRemark,
            sellerRemark: data.sellerRemark ,
            shipmentTime: data.shipmentTime,
            goodsList: data.printProductList
          };

          // 生成二维码
          this.$nextTick(() => {
            this.generateQRCode(this.printDeliveryDialog.deliveryData.shipmentCode);
            this.printDeliveryDialog.loading = false;
          });
        }
        
        this.printDeliveryDialog.loading = false;
        this.printDeliveryDialog.visible = true;
      })
    },

    // 确认打印发货单
    confirmPrintDelivery() {
      this.printDeliveryDialog.printing = true;
      // 调用打印发货单API todo
        this.$modal.msgWarning("功能开发中");
    },

    // 打印物流单 只能选择一条数据进行修改
    handlePrintLogistics() {
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择要打印的物流单");
        return;
      }
      if (this.ids.length > 1) {
        this.$modal.msgError("只能选择一条数据进行打印");
        return;
      }

      this.printLogisticsDialog.visible = true;
      this.printLogisticsDialog.loading = true;
      this.printLogisticsDialog.deliveryIds = this.ids;
        // 调用获取物流单预览API
      printLogistics(this.ids)
        .then((res) => {
          this.printLogisticsDialog.previewUrl = res.data;
        })
        .catch(() => {
          this.$modal.msgError("获取物流单预览失败");
        })
        .finally(() => {
          this.printLogisticsDialog.loading = false;
        });
    },

    // 确认打印物流单
    confirmPrintLogistics() {
      this.printLogisticsDialog.printing = true;
      // 调用打印物流单API todo
        this.$modal.msgWarning("功能开发中");
    },

    // 修改物流/发货信息
    handleUpdateLogisticsInfo() {
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择要修改的数据");
        return;
      }
      
      if (this.ids.length > 1) {
        this.$modal.msgError("只能选择一条数据进行修改");
        return;
      }

      const shipmentId = this.ids[0];
      
      // 打开弹窗并设置loading状态
      this.updateLogisticsDialog.visible = true;
      this.updateLogisticsDialog.loading = true;

      // 初始化表单数据
      this.updateLogisticsForm = {
        logisticsItems: [],
        receivingInfo: {},
        deliveryIds: this.ids
      };

      // 并行调用两个API获取数据
      Promise.all([
        getConsigneeInfo(shipmentId),
        getPackageLogisticsInfo(shipmentId)
      ])
        .then(([consigneeRes, packageRes]) => {
          // 处理收货信息
          if (consigneeRes.data) {
            this.updateLogisticsForm.receivingInfo = {
              consignee: consigneeRes.data.consignee,
              phone: consigneeRes.data.phone,
              tel: consigneeRes.data.tel,
              realName: consigneeRes.data.realName,
              idCard: consigneeRes.data.idCard,
              addrBrief: consigneeRes.data.addrBrief,
              address: consigneeRes.data.address,
              postcode: consigneeRes.data.postcode,
              remark: consigneeRes.data.remark,
              id: consigneeRes.data.id
            };
          }

          // 处理包裹物流信息
          if (packageRes.data && Array.isArray(packageRes.data)) {
            this.updateLogisticsForm.logisticsItems = packageRes.data.map(item => ({
              id: item.shipmentId,
              shipmentCode: item.shipmentCode,
              expressCode: item.expressNo,
              expressCompany: item.expressCompany
            }));
          } else {
            this.updateLogisticsForm.logisticsItems = [];
          }
        })
        .finally(() => {
          this.updateLogisticsDialog.loading = false;
        });
    },

    // 确认修改物流/发货信息
    confirmUpdateLogistics() {
      // 验证必填字段
      if (!this.updateLogisticsForm.receivingInfo.consignee) {
        this.$modal.msgError("收货人不能为空");
        return;
      }
      if (!this.updateLogisticsForm.receivingInfo.tel) {
        this.$modal.msgError("收货手机不能为空");
        return;
      }
      if (!this.updateLogisticsForm.receivingInfo.address) {
        this.$modal.msgError("收货地址不能为空");
        return;
      }

      this.updateLogisticsDialog.loading = true;
      
      // 构造API参数
      const params = {
        // 包裹物流信息
        packages: this.updateLogisticsForm.logisticsItems.map(item => ({
          shipmentId: item.id,
          expressNo: item.expressCode,
          expressCompany: item.expressCompany
        })),
        // 收货信息对象
        saleOrderDelivery: {
          shipmentId: this.ids[0],
          consignee: this.updateLogisticsForm.receivingInfo.consignee,
          phone: this.updateLogisticsForm.receivingInfo.phone,
          tel: this.updateLogisticsForm.receivingInfo.tel,
          realName: this.updateLogisticsForm.receivingInfo.realName,
          idCard: this.updateLogisticsForm.receivingInfo.idCard,
          addrBrief: this.updateLogisticsForm.receivingInfo.addrBrief,
          address: this.updateLogisticsForm.receivingInfo.address,
          postcode: this.updateLogisticsForm.receivingInfo.postcode,
          remark: this.updateLogisticsForm.receivingInfo.remark,
          id: this.updateLogisticsForm.receivingInfo.id
        }
      };

      updateLogisticsInfo(params)
        .then(() => {
          this.$modal.msgSuccess("物流/收货信息修改成功");
          this.updateLogisticsDialog.visible = false;
          this.getList();
        })
        .catch(() => {
          this.$modal.msgError("物流/收货信息修改失败");
        })
        .finally(() => {
          this.updateLogisticsDialog.loading = false;
        });
    },

    // 批量修改打印状态
    handlePrintStatusCommand(type) {
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择数据");
        return;
      }

      let statusMessage = "";
      let updateData = {};

      switch (type) {
        case "deliveryUnprinted":
          statusMessage = "发货单未打印";
          updateData = { 
            expressBillPrinted: false
           };
          break;
        case "deliveryPrinted":
          statusMessage = "发货单已打印";
          updateData = { 
            expressBillPrinted: true, 
          };
          break;
        case "logisticsUnprinted":
          statusMessage = "物流单未打印";
          updateData = { shipmentBillPrinted: false };
          break;
        case "logisticsPrinted":
          statusMessage = "物流单已打印";
          updateData = { 
            shipmentBillPrinted: true, 
          };
          break;
      }
      updateData.shipmentIds = this.ids;

      this.$confirm(`确定要将选中的数据修改为${statusMessage}吗？`)
        .then(() => {
          confirmLogisticsPrinted(updateData)
            .then(() => {
              this.getList();
              this.$modal.msgSuccess("打印状态修改成功");
            })
            .finally(() => {
              this.loading = false;
            });
        })
        .catch(() => { });
    },

    // 批量修改物流公司
    handleBatchUpdateExpress() {
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择数据");
        return;
      }
      this.batchDialog.type = "express";
      this.batchDialog.visible = true;
      // 清空表单
      this.batchForm = { expressCompany: "" };
      
      // 如果只选了一条记录，预填当前物流公司
      if (this.ids.length === 1) {
        const selectedRow = this.tableData.find(item => item.id === this.ids[0]);
        if (selectedRow) {
          this.batchForm.expressCompany = selectedRow.expressCompany || "";
        }
      }
    },

    // 多包裹处理
    handleMultiPackageCommand(type) {
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择数据");
        return;
      }
      
      if (this.ids.length > 1) {
        this.$modal.msgError("只能选择一条数据进行操作");
        return;
      }

      const selectedRow = this.tableData.find(item => item.id === this.ids[0]);
      if (!selectedRow) {
        this.$modal.msgError("未找到选中的数据");
        return;
      }

      const isMultiPackage = selectedRow.multiPackage && selectedRow.multiPackage !== null;

      switch (type) {
        case "getMultiPackage":
          if (isMultiPackage) {
            this.$modal.msgWarning("已经是多包裹");
            return;
          }
          this.multiPackageDialog.type = 'get';
          this.multiPackageDialog.packageCount = 2;
          this.multiPackageDialog.visible = true;
          break;
          
        case "updateMultiPackage":
          if (!isMultiPackage) {
            this.$modal.msgWarning("请选择多包裹数据");
            return;
          }
          this.multiPackageDialog.type = 'update';
          this.multiPackageDialog.packageCount = 2;
          this.multiPackageDialog.visible = true;
          break;
          
        case "cancelMultiPackage":
          if (!isMultiPackage) {
            this.$modal.msgWarning("请选择多包裹数据");
            return;
          }
          this.multiPackageDialog.type = 'cancel';
          this.multiPackageDialog.visible = true;
          break;
      }
    },

    // 获取多包裹弹窗标题
    getMultiPackageDialogTitle() {
      switch (this.multiPackageDialog.type) {
        case 'get':
          return '获取多包裹';
        case 'update':
          return '修改多包裹';
        case 'cancel':
          return '取消多包裹';
        default:
          return '多包裹操作';
      }
    },

    // 确认多包裹操作
    confirmMultiPackageOperation() {
      const shipmentId = this.ids[0];
      
      // 验证包裹数量
      if ((this.multiPackageDialog.type === 'get' || this.multiPackageDialog.type === 'update') && 
          (!this.multiPackageDialog.packageCount || this.multiPackageDialog.packageCount < 2)) {
        this.$modal.msgError("包裹数量不能小于2");
        return;
      }

      this.multiPackageDialog.loading = true;

      let apiPromise;
      let params;

      switch (this.multiPackageDialog.type) {
        case 'get':
          params = {
            id: shipmentId,
            count: this.multiPackageDialog.packageCount
          };
          apiPromise = getMultiPackage(params);
          break;
          
        case 'update':
          params = {
            id: shipmentId,
            count: this.multiPackageDialog.packageCount
          };
          apiPromise = updateMultiPackage(params);
          break;
          
        case 'cancel':
          params = {
            id: shipmentId
          };
          apiPromise = cancelMultiPackage(params);
          break;
      }

      apiPromise
        .then(() => {
          const operationName = this.multiPackageDialog.type === 'get' ? '获取' : 
                               this.multiPackageDialog.type === 'update' ? '修改' : '取消';
          this.$modal.msgSuccess(`${operationName}多包裹成功`);
          this.multiPackageDialog.visible = false;
          this.getList(); // 刷新列表数据
        })
        .catch(() => {
          const operationName = this.multiPackageDialog.type === 'get' ? '获取' : 
                               this.multiPackageDialog.type === 'update' ? '修改' : '取消';
          this.$modal.msgError(`${operationName}多包裹失败`);
        })
        .finally(() => {
          this.multiPackageDialog.loading = false;
        });
    },

    // 作废发货单
    handleCancelDelivery() {
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择要作废的发货单");
        return;
      }

      this.$confirm("确定要作废选中的发货单吗？此操作不可恢复！")
        .then(() => {
          cancelDelivery({ shipmentIds: this.ids })
            .then((res) => {
              if (res.code === 200) {
                this.$modal.msgSuccess("发货单作废成功");
                this.getList();
              } 
            })
        })
        .catch(() => { });
    },

    // 填充物流单号
    handleFillLogisticsCode() {
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择要填充物流单号的记录");
        return;
      }

      // 只允许选择一条数据
      if (this.ids.length > 1) {
        this.$modal.msgError("只能选择一条记录进行填充物流单号");
        return;
      }

      this.fillLogisticsDialog.visible = true;
      this.fillLogisticsDialog.loading = true;
      
      // 初始化表单数据
      this.fillLogisticsForm = {
        packageList: [],
        deliveryIds: this.ids,
      };

      // 获取包裹物流信息
      getPackageLogisticsInfo(this.ids[0])
        .then((res) => {
          if (res.code === 200) {
            this.fillLogisticsForm.packageList = res.data.map(item => ({
              shipmentId: item.shipmentId,
              shipmentCode: item.shipmentCode || '',
              packageCode: item.packageCode || '',
              expressNo: item.expressNo || '', // 可以修改的物流单号
            }));
          } else{
            this.fillLogisticsForm.packageList = []
          }
        })
        .finally(() => {
          this.fillLogisticsDialog.loading = false;
        });
    },

    // 确认填充物流单号
    confirmFillLogistics() {
      // 验证所有物流单号是否已填写
      const emptyRows = this.fillLogisticsForm.packageList.filter(item => !item.expressNo || item.expressNo.trim() === '');
      if (emptyRows.length > 0) {
        this.$modal.msgError("请为所有包裹填写物流单号");
        return;
      }

      // 构造API参数
      const params = {
        packages: this.fillLogisticsForm.packageList.map(item => ({
          shipmentId: item.shipmentId,
          expressNo: item.expressNo.trim(),
        }))
      };

      this.fillLogisticsDialog.loading = true;
      fillLogisticsCode(params)
        .then(() => {
          this.$modal.msgSuccess("物流单号填充成功");
          this.fillLogisticsDialog.visible = false;
          // 刷新列表数据
          this.getList();
        })
        .catch(() => {
          this.$modal.msgError("物流单号填充失败");
        })
        .finally(() => {
          this.fillLogisticsDialog.loading = false;
        });
    },

    // 导出功能
    handleExportCommand(type) {
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择要导出的数据");
        return;
      }

      // const exportText = type === "exportDelivery" ? "发货单数据" : "包裹数据";
      // this.$modal.msgSuccess(`${exportText}导出成功，请在浏览器下载栏查看`);
      this.$modal.msgWarning(`功能开发中`);
    },

    // 补打物流单 与打印物流单逻辑相同 只能选择一条数据进行修改
    handleReprintLogistics() {
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择要补打的物流单");
        return;
      }
      if (this.ids.length > 1) {
        this.$modal.msgError("只能选择一条数据进行补打");
        return;
      }

      // 复用打印物流单的逻辑，直接调用
      this.handlePrintLogistics();
    },

    // 批量操作
    handleBatchCommand(type) {
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择数据");
        return;
      }
      this.batchDialog.type = type;
      this.batchDialog.visible = true;
      // 清空表单
      this.batchForm = { warehouseName: "", expressCompany: "" };
    },

    handleBatchSubmit() {
      if (this.batchDialog.type === "warehouse") {
        if (!this.batchForm.warehouseName) {
          this.$modal.msgError("请输入新仓库名称");
          return;
        }
        const params = {
          warehouseName: this.batchForm.warehouseName,
          orderIds: this.ids,
        };
        this.loading = true;
        
        // 模拟API调用
        setTimeout(() => {
          // 功能开发中
          this.$modal.msgSuccess("功能开发中");

          // this.$modal.msgSuccess("批量修改仓库成功");
          this.batchDialog.visible = false;
          this.loading = false;
        }, 500);
        return;
      }
      if (this.batchDialog.type === "express") {
        if (!this.batchForm.expressCompany) {
          this.$modal.msgError("请输入新物流公司");
          return;
        }
        const params = {
          expressCompany: this.batchForm.expressCompany,
          orderIds: this.ids,
        };
        this.loading = true;
        
        // 模拟API调用
        setTimeout(() => {
          // 功能开发中
          this.$modal.msgSuccess("功能开发中");
          // this.$modal.msgSuccess("批量修改物流公司成功");
          this.batchDialog.visible = false;
          this.loading = false;
        }, 500);
        return;
      }
      if (this.batchDialog.type === "stock") {
        const params = {
          orderIds: this.ids,
          inStock: true,
        };
        this.loading = true;
        updateStock(params)
          .then(() => {
            this.$modal.msgSuccess("批量转为现货订单成功");
            this.batchDialog.visible = false;
            this.getList();
          })
          .catch(() => {
            this.$modal.msgError("批量转为现货订单失败");
          })
          .finally(() => {
            this.loading = false;
          });
        return;
      }
      if (this.batchDialog.type === "bizUser") {
        if (!this.batchForm.bizUserId) {
          this.$modal.msgError("请选择业务员");
          return;
        }
        // 假设有 updateBizUser 批量接口
        const params = {
          bizUserId: this.batchForm.bizUserId,
          orderIds: this.ids,
        };
        this.loading = true;
        (this.$api?.mes?.sales?.updateBizUser || (() => Promise.resolve()))(
          params
        )
          .then(() => {
            this.$modal.msgSuccess("批量修改业务员成功");
            this.batchDialog.visible = false;
            this.getList();
          })
          .catch(() => {
            this.$modal.msgError("批量修改业务员失败");
          })
          .finally(() => {
            this.loading = false;
          });
        return;
      }
      if (this.batchDialog.type === "extraInfo") {
        if (!this.batchForm.extraInfo) {
          this.$modal.msgError("请输入附加信息");
          return;
        }
        // 假设有 updateExtraInfo 批量接口
        const params = {
          extraInfo: this.batchForm.extraInfo,
          orderIds: this.ids,
        };
        this.loading = true;
        (this.$api?.mes?.sales?.updateExtraInfo || (() => Promise.resolve()))(
          params
        )
          .then(() => {
            this.$modal.msgSuccess("批量修改附加信息成功");
            this.batchDialog.visible = false;
            this.getList();
          })
          .catch(() => {
            this.$modal.msgError("批量修改附加信息失败");
          })
          .finally(() => {
            this.loading = false;
          });
        return;
      }
      if (this.batchDialog.type === "expectDelivery") {
        if (!this.batchForm.expectDelivery) {
          this.$modal.msgError("请选择预计发货时间");
          return;
        }
        // 假设有 updateExpectDelivery 批量接口
        const params = {
          expectDelivery: this.batchForm.expectDelivery,
          orderIds: this.ids,
        };
        this.loading = true;
        (
          this.$api?.mes?.sales?.updateExpectDelivery ||
          (() => Promise.resolve())
        )(params)
          .then(() => {
            this.$modal.msgSuccess("批量修改预计发货时间成功");
            this.batchDialog.visible = false;
            this.getList();
          })
          .catch(() => {
            this.$modal.msgError("批量修改预计发货时间失败");
          })
          .finally(() => {
            this.loading = false;
          });
        return;
      }
    },

    handleBatchCancel() {
      this.batchDialog.visible = false;
    },
    getDefaultDateRange() {
      const today = new Date();
      const thirtyDaysAgo = new Date();
      thirtyDaysAgo.setDate(today.getDate() - 30);
      const formatDate = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        return `${year}-${month}-${day}`;
      };
      return [formatDate(thirtyDaysAgo), formatDate(today)];
    },
    getList() {
      this.loading = true;
      // 处理日期范围
      if (
        this.createDate &&
        this.createDate.length === 2
      ) {
        this.queryParams.startDate = this.createDate[0];
        this.queryParams.endDate = this.createDate[1];
      }
      this.queryParams.isCancel = this.isCancel ? 1 : 0;
      this.queryParams.intercepted = this.intercepted ? 1 : 0;
      listPrintManagement(this.queryParams)
        .then((response) => {
          this.tableData = response.rows;
          this.$nextTick(() => {
            if (this.tableData.length > 0) {
              this.$refs.tableRef.setCurrentRow(this.tableData[0]);
            }
          });
          if (response.rows?.length > 0) {
            this.cellId = response.rows[0].id;
          }
          this.total = response.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    reset() {
      this.form = {};
      this.autoGenFlag = false;
      // this.$refs.form.resetFields();
    },
    handleAdd() {
      this.open = true;
      this.title = "新增";
      this.reset();
    },

    // 修改功能：选中一条数据，获取详情，弹窗回显，保存时调editSalesOrder
    async handleEdit() {
      if (!this.ids || this.ids.length !== 1) {
        this.$modal.msgError("请选择一条要修改的数据");
        return;
      }
      const id = this.ids[0];
      try {
        // 假设有 getSalesOrderDetail 接口，返回完整订单详情（含商品、支付、收货信息）
        const { data } = (await this.$api?.mes?.sales?.getSalesOrderDetail)
          ? await this.$api.mes.sales.getSalesOrderDetail(id)
          : await this.$axios.get(`/mes/sales/saleOrder/${id}`);
        // 回显主表单
        this.form = { ...data };
        this.title = "修改";
        this.open = true;
        this.$nextTick(() => {
          // 回显商品、支付、收货信息到各tab组件
          if (this.$refs.goodsTab && data.goodsList) {
            this.$refs.goodsTab.setTableData?.(data.goodsList);
          }
          if (this.$refs.payTab && data.payList) {
            this.$refs.payTab.setTableData?.(data.payList);
          }
          if (this.$refs.addressTab && data.addressInfo) {
            this.$refs.addressTab.setFormData?.(data.addressInfo);
          }
        });
      } catch (e) {
        this.$modal.msgError("获取订单详情失败");
      }
    },
    handleDelete(row) {
      if (this.ids.length == 0) {
        this.$modal.msgError("请选择要删除的数据");
        return;
      }
      const ids = this.ids;
      this.$modal
        .confirm("是否确认删除选中的订单？")
        .then(() => {
          return deleteOrder(ids);
        })
        .then(() => {
          this.getList();
          this.ids = [];
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    handleUpdate(row) {
      console.log(row);
      this.title = "修改";
      this.reset();
      this.open = true;
      this.form = { ...row };
    },
    handleEnable(action) {
      if (this.ids.length === 0 && action !== "import") {
        this.$modal.msgError("请选择数据");
        return;
      }
      if (action === "copy") {
        this.$modal.msgWarning("暂无复制接口");
        return;
      }
      if (action === "audit" || action === "auditFalse") {
        const ok = action === "audit";
        this.$prompt("请输入审核备注", ok ? "订单审核" : "订单反审核", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          inputType: "textarea",
          inputPlaceholder: "请输入备注（可选）",
        })
          .then(({ value }) => {
            const reqs = this.ids.map((orderId) => {
              return orderAudit({ ok, orderId, remark: value || "" });
            });
            Promise.all(reqs)
              .then(() => {
                this.$modal.msgSuccess(ok ? "审核成功" : "反审核成功");
                this.getList();
              })
              .catch(() => { });
          })
          .catch(() => { });
        return;
      }
      // 订单导入弹窗已集成el-upload，无需再触发input
      if (action === "import") {
        this.batchDialog.type = "import";
        this.batchDialog.visible = true;
        return;
      }
      let confirmMsg = "";
      switch (action) {
        case "cancel":
          confirmMsg = "确定要作废选中的订单吗？";
          break;
        case "intercept":
          confirmMsg = "确定要拦截选中的订单吗？";
          break;
        case "batch":
          confirmMsg = "确定要批量操作选中的订单吗？";
          break;
        default:
          confirmMsg = "确定要执行该操作吗？";
      }
      this.$confirm(confirmMsg)
        .then(() => {
          this.$modal.msgSuccess("操作成功");
          this.getList();
        })
        .catch(() => { });
    },
    // 订单导入el-upload自定义上传
    handleImportUpload(param) {
      if (!param.file) return;
      const formData = new FormData();
      formData.append("file", param.file);
      this.loading = true;
      importSellOrder(formData)
        .then((res) => {
          this.$modal.msgSuccess("导入成功");
          this.batchDialog.visible = false;
          this.getList();
        })
        .catch(() => {
          this.$modal.msgError("导入失败");
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleToExamine(row) {
      console.log(row);
    },
    handleAntiAudit(row) {
      console.log(row);
    },
    handleQuery() {
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        shipmentCode: null,
        platformOrderCode: null,
        clientName: null,
        consignee: null,
        warehouseName: null,
        shopName: null,
        expressCode: null,
        expressCompany: null,
        orderStatus: null,
        printStatus: null,
      };
      this.createDate = this.getDefaultDateRange();
      this.isCancel = false;
      this.intercepted = false;
      this.getList();
    },
    submitForm() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          this.form.collect = this.form.collect ? 1 : 0;
          this.form.distributor = this.form.distributor ? 1 : 0;
          // 统一收集弹窗内所有表单数据
          // 商品信息，补充自动计算字段
          let goodsList =
            this.$refs.goodsTab && this.$refs.goodsTab.tableData
              ? JSON.parse(JSON.stringify(this.$refs.goodsTab.tableData))
              : [];
          // 获取商品tab内自动计算方法
          const goodsTab = this.$refs.goodsTab;
          if (goodsTab && Array.isArray(goodsList)) {
            goodsList = goodsList.map((row) => {
              // 兼容组件内methods
              let stdAmount = row.stdAmount;
              let actualAmount = row.actualAmount;
              let profitAmount = row.profitAmount;
              if (typeof goodsTab.calcStdAmount === "function") {
                stdAmount = goodsTab.calcStdAmount(row);
              }
              if (typeof goodsTab.calcActualAmount === "function") {
                actualAmount = goodsTab.calcActualAmount(row);
              }
              if (typeof goodsTab.calcProfitAmount === "function") {
                profitAmount = goodsTab.calcProfitAmount(row);
              }
              return {
                ...row,
                stdAmount,
                actualAmount,
                profitAmount,
              };
            });
          }
          // 支付信息
          const payList =
            this.$refs.payTab && this.$refs.payTab.tableData
              ? JSON.parse(JSON.stringify(this.$refs.payTab.tableData))
              : [];
          // 收货信息
          let addressInfo = {};
          if (this.$refs.addressTab && this.$refs.addressTab.form) {
            addressInfo = JSON.parse(
              JSON.stringify(this.$refs.addressTab.form)
            );
          } else if (
            this.$refs.addressTab &&
            this.$refs.addressTab.$refs &&
            this.$refs.addressTab.$refs.form &&
            this.$refs.addressTab.$refs.form.model
          ) {
            // 兼容el-form嵌套
            addressInfo = JSON.parse(
              JSON.stringify(this.$refs.addressTab.$refs.form.model)
            );
          }
          // 组装到form对象
          const submitData = {
            ...this.form,
            goodsList,
            payList,
            addressInfo,
          };
          // 判断是新增还是修改
          if (this.form.id != null) {
            // 修改
            editSalesOrder(submitData).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // 新增
            addSalesOrder(submitData).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 订单拦截/取消拦截下拉处理
    handleInterceptCommand(type) {
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择数据");
        return;
      }
      let confirmMsg = "";
      let apiFunc = null;
      if (type === "intercept") {
        confirmMsg = "确定要拦截选中的订单吗？";
        // 假设有 orderIntercept 批量接口
        apiFunc =
          this.$api?.mes?.sales?.orderIntercept || (() => Promise.resolve());
      } else if (type === "cancelIntercept") {
        confirmMsg = "确定要取消拦截选中的订单吗？";
        // 假设有 orderCancelIntercept 批量接口
        apiFunc =
          this.$api?.mes?.sales?.orderCancelIntercept ||
          (() => Promise.resolve());
      }
      if (!apiFunc) return;
      this.$confirm(confirmMsg)
        .then(() => {
          this.loading = true;
          apiFunc({ orderIds: this.ids })
            .then(() => {
              this.$modal.msgSuccess(
                type === "intercept" ? "拦截成功" : "取消拦截成功"
              );
              this.getList();
            })
            .catch(() => {
              this.$modal.msgError(
                type === "intercept" ? "拦截失败" : "取消拦截失败"
              );
            })
            .finally(() => {
              this.loading = false;
            });
        })
        .catch(() => { });
    },
    cancel() {
      this.$refs["form"].resetFields();
      this.open = false;
    },
    cellClickEvent({ row }) {
      this.cellId = row.id;
      // this.bottomTableData = row.poStatus;
      this.handleClick({ name: "1" });
      console.log(row);
    },
    checkboxChangeEvent(checked) {
      this.ids = checked.records.map((item) => item.id);
      console.log(checked.records, this.ids);
    },
    checkboxAll(checked) {
      this.ids = checked.records.map((item) => item.id);
      console.log(checked.records, this.ids);
    },
    handleClick(tab, event) {
      switch (tab.name) {
        case "1":
          console.log("基础信息");
          break;
        case "2":
          console.log("2");
          break;
        default:
          break;
      }
    },
    // 订单明细
    //   getBaseInfoList(params={pageNum:1,pageSize:10}){
    //     detailPurchaseOrder(this.cellId, params).then(response => {
    //       this.baseTotal = response.total;
    //       console.log(response);
    //     })
    //   },
    handleUpload() {
      this.upload.title = "数据导入";
      this.upload.open = true;
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    handlePrint(row) {
      console.log(row, window.location);
      window.open(
        window.location.origin +
        window.location.pathname +
        "#/printTemplate?poId=" +
        row.id +
        "&type=in",
        "_blank"
      );
    },
    submitForm1() {
      this.$confirm("确定要修改吗？").then(() => {
        editSalesOrder(this.form).then((response) => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      });
    },
    importTemplate() {
      // window.open("/excel_templates/shop_templates.xls", "_blank");
      this.$message.info("请联系管理员获取导入模板");
    },
    handleCancelOrder() {
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择要作废的订单");
        return;
      }
      this.$modal
        .confirm("确定要作废选中的订单吗？")
        .then(() => {
          return cancelOrder(this.ids);
        })
        .then(() => {
          this.$modal.msgSuccess("订单作废成功");
          this.getList();
        })
        .catch(() => { });
    },

    // 生成二维码
    generateQRCode(text) {
      const canvas = this.$refs.qrCanvas;
      if (!canvas) return;
      
      const ctx = canvas.getContext('2d');
      const size = 80;
      const moduleCount = 21; // 二维码模块数，这里简化处理
      const moduleSize = Math.floor(size / moduleCount);
      
      // 清空画布
      ctx.clearRect(0, 0, size, size);
      ctx.fillStyle = '#000';
      
      // 简化的二维码生成（实际项目中建议使用qrcode.js等库）
      // 这里只是生成一个简单的黑白方块图案作为示例
      for (let i = 0; i < moduleCount; i++) {
        for (let j = 0; j < moduleCount; j++) {
          // 简单的伪随机算法生成二维码图案
          const seed = (text.charCodeAt(i % text.length) + i * j) % 7;
          if (seed > 3) {
            ctx.fillRect(i * moduleSize, j * moduleSize, moduleSize, moduleSize);
          }
        }
      }
      
      // 添加三个定位点
      this.drawFinderPattern(ctx, 0, 0, moduleSize);
      this.drawFinderPattern(ctx, (moduleCount - 7) * moduleSize, 0, moduleSize);
      this.drawFinderPattern(ctx, 0, (moduleCount - 7) * moduleSize, moduleSize);
    },

    // 绘制二维码定位点
    drawFinderPattern(ctx, x, y, moduleSize) {
      ctx.fillStyle = '#000';
      // 外框
      ctx.fillRect(x, y, 7 * moduleSize, 7 * moduleSize);
      // 内部白色
      ctx.fillStyle = '#fff';
      ctx.fillRect(x + moduleSize, y + moduleSize, 5 * moduleSize, 5 * moduleSize);
      // 中心黑点
      ctx.fillStyle = '#000';
      ctx.fillRect(x + 2 * moduleSize, y + 2 * moduleSize, 3 * moduleSize, 3 * moduleSize);
    },
  },
};
</script>

<style scoped>
::v-deep.el-date-editor.el-input {
  width: 264px;
}
</style>

<style lang="scss" scoped>
.app-container {
  &-main {
    margin-bottom: 10px;
  }

  &-footer {
    margin-top: 20px;

    &-title {
      display: flex;
      margin-bottom: 20px;

      &-item {
        cursor: pointer;
        padding: 5px 20px;
        border-radius: 8px;
      }

      .active {
        background-color: aqua;
      }
    }
  }
}

.el-select {
  width: 100%;
}

.upload-area {
  margin: 20px 0;

  // 修复上传区域宽度问题
  ::v-deep .el-upload {
    width: 100%;
  }

  ::v-deep .el-upload-dragger {
    width: 100%;
    box-sizing: border-box;
  }

  // 确保提示文字与上传区域宽度一致
  ::v-deep .el-upload__tip {
    width: 100%;
    box-sizing: border-box;
    margin-top: 10px;
    text-align: left;
    display: flex;
    align-items: center;
    flex-direction: column;

    .el-upload__tip {
      margin-bottom: 5px;
    }

    span {
      display: block;
      margin-bottom: 5px;
    }
  }
}

.print-preview {
  min-height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;

  &-image {
    max-width: 100%;
    max-height: 400px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
}

.no-preview {
  color: #999;
  font-size: 16px;
  text-align: center;
}

/* 物流信息表格样式 */
.logistics-table {
  margin-bottom: 15px;
}

.logistics-table .el-table {
  border: 1px solid #EBEEF5;
  border-collapse: collapse;
}

.logistics-table th {
  background-color: #F5F7FA;
  color: #606266;
  padding: 12px 0;
  text-align: center;
  border-bottom: 1px solid #EBEEF5;
  font-weight: 500;
}

.logistics-table td {
  padding: 8px;
  text-align: center;
  border-bottom: 1px solid #EBEEF5;
}

.logistics-table tr:last-child td {
  border-bottom: none;
}

/* 发货单打印样式 */
.delivery-print-container {
  padding: 20px;
  background: white;
}

.delivery-print-content {
  max-width: 800px;
  margin: 0 auto;
  font-family: SimSun, serif;
}

.delivery-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 30px;
  position: relative;
}

.delivery-title {
  display: flex;
  align-items: center;
  flex: 1;
  justify-content: center;
}

.title-number {
  width: 30px;
  height: 30px;
  background: #000;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: bold;
  margin: 0 10px;
}

.title-text {
  font-size: 28px;
  font-weight: bold;
  margin: 0;
  text-align: center;
}

.delivery-qrcode {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: absolute;
  right: 0;
  top: 0;
}

.qr-code {
  border: 2px solid #000;
  padding: 2px;
  margin-bottom: 5px;
}

.delivery-code {
  font-size: 12px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 2px;
}

.delivery-time {
  font-size: 10px;
  text-align: center;
}

.delivery-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30px;
  font-size: 14px;
  line-height: 1.8;
  width: 74%;
}

.info-left {
  flex: 1;
  margin-right: 40px;
}

.info-right {
  width: 200px;
}

.info-row {
  margin-bottom: 8px;
  display: flex;
  align-items: flex-start;
}

.info-row .label {
  font-weight: bold;
  min-width: 80px;
  color: #333;
}

.info-row .value {
  flex: 1;
  word-break: break-all;
}

.delivery-table {
  margin-top: 20px;
}

.goods-table {
  width: 100%;
  border-collapse: collapse;
  border: 2px solid #000;
  font-size: 14px;
}

.goods-table th {
  background: #f5f5f5;
  border: 1px solid #000;
  padding: 10px 8px;
  text-align: center;
  font-weight: bold;
}

.goods-table td {
  border: 1px solid #000;
  padding: 8px;
  text-align: center;
  vertical-align: middle;
}

.goods-table tbody tr:nth-child(odd) {
  background: #fafafa;
}

@media print {
  .delivery-print-container {
    padding: 0;
  }
  
  .dialog-footer {
    display: none !important;
  }
}

/* 填充物流单号表格样式 */
.fill-logistics-table {
  .el-table th {
    background-color: #f5f7fa;
    color: #606266;
    font-weight: 500;
  }

  .el-table td {
    padding: 12px 0;
  }

  .el-input {
    width: 100%;
  }

  .el-input__inner {
    border-radius: 4px;
    font-size: 13px;
  }
}

/* 物流单号输入框样式 */
::v-deep .fill-logistics-table .el-table .el-input {
  .el-input__inner {
    height: 32px;
    line-height: 32px;
    padding: 0 8px;
  }
}

/* 多包裹弹窗样式 */
.multi-package-dialog {
  .el-input-number {
    width: 100%;
  }

  .el-alert {
    margin-top: 15px;
  }
}

/* 多包裹确认内容样式 */
.multi-package-confirm {
  text-align: center;
  padding: 20px 0;
  font-size: 14px;
  color: #606266;
  line-height: 1.5;
}
</style>